<?php
namespace app\admin\controller;
use app\admin\controller\Base;
use app\api\logic\Weixin;
use think\Db;
use think\Image;
use think\Request;
use think\validate;
class Goods extends Base
{

    
    // 商品分类 - 列表
    public function cateList()
    {

        $where=[];
        $where = ['admin_id'=>$this->accountId];
        $res = db('goods_category')->where($where)->order('sort desc')->paginate(100, false);
        //dump($res);exit;
        $page = $res->render();
        $res = getCategory($res, 0);
        $this->assign('res', $res);
        $this->assign('page', $page);
        return $this->fetch();
    }

    // 商品分类 - 编辑
    public function cateEdit($id,Request $request)
    {
        $sk = $this->accountId;
        if (request()->isPost()) {
            $post = request()->only(['parent_id', 'title', 'description', 'sort','img'], 'post');
            //dump($post);exit;
            if (empty($post['parent_id'])) {
                unset($post['parent_id']);
            }
            //广告图上传开始
               
            if (!empty($_FILES['img']['tmp_name'])) {
                // 获取表单上传文件 
                $file = request()->file('img');
                //dump($file);exit;
                // 移动到框架应用根目录/public/uploads/ 目录下'
                $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
                // $info = $file->move('/home/www/upload/');
                //dump($info);exit;
                if($info){
                // 成功上传后 获取上传信息
                // 输出 
                // $img ='http://127.0.0.1/applet/'.'public' . DS . 'uploads' . '/' . $info->getSaveName();
                $img = 'uploads' . '/' . $info->getSaveName();
                //dump($img);exit;

                $data['img'] = $img;
                //dump($post['img']);exit;
                }else{
                    err('', $file->getError());
                }
            }
            //广告图上传结束
            $data['title'] = $post['title'];
            $data['description'] = $post['description'];
            $data['sort'] = $post['sort'];
            $where = [];
            $where['id'] = $id;
            $where['admin_id'] = $this->accountId;
            $res = db('goods_category')->where($where)->update($data);
            //dump($data);exit;
            if ($res) {
                suc('','修改成功');
            }else{
                suc('','修改失败');
            }
        }

        $where = ['admin_id'=>$this->accountId];
        $cate = db('goods_category')->where($where)->limit(100)->select();
        foreach ($cate as $key=>$value) {
            if ($value['id'] == $id) {
                $res = $cate[$key];
            }
        }
        $cate = getCategory($cate, 0);
        $this->assign('cate', $cate);
        $this->assign('res', $res);
        return $this->fetch();
        
    }
    
    // 商品分类 - 增加
    public function cateAdd(Request $request)
    {
        $sk = $this->accountId;
        if (request()->isPost()) {
            $post = request()->only(['parent_id', 'title', 'description','content', 'display', 'sort','img'], 'post');
              //广告图上传开始
             if ($_FILES['img']['tmp_name']) {
                // 获取表单上传文件 
                $file = request()->file('img');
                //dump($file);exit;
                // 移动到框架应用根目录/public/uploads/ 目录下'
                $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
                // $info = $file->move('/home/www/upload/');
                if($info){
                // 成功上传后 获取上传信息
                // 输出 
                // $img ='http://127.0.0.1/applet/'.'public' . DS . 'uploads' . '/' . $info->getSaveName();
                $id_imgs = 'uploads' . '/' . $info->getSaveName();
                $post['img'] = $id_imgs;
            }
        }
           
            //广告图上传结束
            $post['admin_id'] = $this->accountId;
            $post['create_time'] = $this->timeStamp;
            $res = db('goods_category')->insert($post);
            //echo DB::name('goods_category')->getlastsql();
            if ($res) {
                suc('','添加成功');
            }else{
                suc('','添加失败');
            }
        }
            $where =[];
            $where['admin_id'] = $this->accountId;
            $cate = db('goods_category')->where($where)->limit(100)->select();
            $cate = getCategory($cate, 0);
            $this->assign('cate', $cate);
            return $this->fetch();

        
    }
    //商品分类删除
    public function catedel($id)
    {
            $where = [];
            $where['id'] = $id;
            $res = db('goods_category')->where($where)->delete();
            suc();
            return $this->fetch();
    }

    // 产品列表
    public function goodsList()
    {

        $where=[];
        $where['admin_id'] = $this->accountId;
        $res = db('goods')->where($where)->order('create_time desc')->paginate($this->page, false);
        //dump($res);exit;
        $page = $res->render();
        $this->assign('res',$res);
        $this->assign('page', $page);
        return $this->fetch();


      }




    // 产品列表-添加
    public function goodsAdd(Request $request)
    {

        
        $sk = $this->accountId;     
       
        if (request()->isPost()) {
            $post = input('post.');
            //dump($post);exit;
            //缩略图
            $cc=$this->thumb_upload($sk,$request);
            $post['thumb'] = $cc;+
            //轮播图
            $mg=$this->imgs_upload($sk,$request);
            $post['imgs'] = $mg;

            if ($this->accountId == '1301') {
                $res['custom_time'] = $post['custom_time'];
                $res['other_id'] = $post['other_id'];

                //图片上传
                if (!empty($_FILES['cover']['tmp_name'])) {
                    // 获取表单上传文件 
                    $file = request()->file('cover');
                    // 移动到框架应用根目录/public/uploads/ 目录下'
                    $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
                    // $info = $file->move('/home/www/upload/');
                    if($info){
                        // 成功上传后 获取上传信息
                        // 输出 
                        // $img ='http://127.0.0.1/applet/'.'public' . DS . 'uploads' . '/' . $info->getSaveName();
                        $cover = 'uploads' . '/' . $info->getSaveName();
                        $res['cover'] = $cover;
                    }
                }
            }

            $res['category_id'] = $post['category_id'];
            $res['title'] =       $post['title'];
            $res['subtitle'] = $post['subtitle'];
            $res['imgs'] = $post['imgs'];
            $res['thumb'] = $post['thumb'];
            $res['price'] = $post['price'];
			// $res['gb_price'] = $post['gb_price'];
            $res['numbers'] = $post['numbers'];
            $res['tags'] = $post['tags'];
            $res['display'] = $post['display'];

            // $res['content'] = $post['content'];
            $res['content'] = isset($post['content'])?$post['content']:'';

            $res['create_time'] = time();
            $res['admin_id'] = $this->accountId;

            // if(empty($res['content'])){
            //     $res['content'] = '';
            // }
            // dump($res['content']);exit;

            $str = db('goods')->insert($res);
             //dump($res);exit;
            if ($str) {
                return 1;
            }else{
                return 2;
            }
        }
        $where =[];
        $where['admin_id'] = $this->accountId;

        $kv = $this->accountId;
        //echo $this->accountId;
        // $where['admin_id'] = $this->accountId;
        $cate = db('goods_category')->where($where)->limit(0,100)->select();
       //echo DB::name('goods_category')->getlastsql();
        $cate = getCategory($cate, 0);
        //var_dump($cate);
        
        $Singer = db('singer')->where("admin_id='{$this->accountId}'")->select();
        $this->assign('Singer', $Singer);
        $this->assign('kv',$kv);
        $this->assign('cate', $cate);
        return $this->fetch();
    }

    //产品列表-删除
    public function goodsDel($id)
    {
        $where = [];
        $where['id'] = $id;
        $where['admin_id'] = $this->accountId;
        $res = db('goods')->where($where)->delete();
        suc();
    }
    //产品列表-编辑
    public function goodsEdit(Request $request,$id)
    {

        $sk = $this->accountId;
        //dump($sk);exit;

        if (request()->isPost()) {

            $post = input('post.');
            //dump($post);exit;
            //缩略图上传
            $cc = $this->thumb_upload($sk, $request);//uploads/1294/admin/图片
            //dump($cc);die;
            $data=array();
            if(!empty($cc)){
                $data['thumb'] = $cc;   //图片赋值

            }
            
            //轮播图上传
            $mg = $this->List_img($sk, $request);  //存储多张图片



            if(!empty($mg)){
                $data['imgs'] = $mg;   //存储多张轮播图

                //获得原本的轮播图信息
                $goods = db('goods')->field('imgs')->where('id='.$id)->find();  //["uploads\/1294\/user\/20170626\图片
                //dump($goods);exit;
                $images=json_decode($goods['imgs']);  //查询数据库有图片的情况下，转换成json格式  

                $new_image=json_decode($data['imgs']);  //把新图片替换成旧图片
                //获得上传的商品图片信息
                //print_r($data['imgs']);exit;
                // dump($images);
                // dump($new_image);
                //图片替换操作
                if(!empty($images)){
                    foreach ($new_image as $key=>$value) {
                        //判断图片不为空的情况下修改
                        if($new_image[$key]!=null && $new_image!=""){
                            $images[$key]=$new_image[$key];  
                        }
                        //保持原有图片格式
                        else{

                        }
                    }
                }
                else{
                    $images=$new_image; //如果图片为空的话就直接用新图片替换成旧图片
                }
                $data['imgs']=json_encode($images);    

            }
          

            $data['category_id'] = $post['category_id'];
            $data['content'] = isset($post['content'])?$post['content']:'';
            $data['price'] = $post['price'];
    		// $data['gb_price'] = $post['gb_price'];
            $data['title'] = $post['title'];
            $data['numbers'] = $post['numbers'];
            $data['tags'] = $post['tags'];
            $data['subtitle'] = $post['subtitle'];
            if ($this->accountId == '1301') {
                $data['other_id'] = $post['other_id'];
                $data['custom_time'] = $post['custom_time'];
                //图片上传
                if (!empty($_FILES['cover']['tmp_name'])) {
                    // 获取表单上传文件 
                    $file = request()->file('cover');
                    // 移动到框架应用根目录/public/uploads/ 目录下'
                    $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
                    // $info = $file->move('/home/www/upload/');
                    if($info){
                        // 成功上传后 获取上传信息
                        // 输出 
                        // $img ='http://127.0.0.1/applet/'.'public' . DS . 'uploads' . '/' . $info->getSaveName();
                        $cover = 'uploads' . '/' . $info->getSaveName();
                        $data['cover'] = $cover;
                    }
                }
            }
            //dump($data['subtitle']);exit;
            $where =[];
            $where['id'] = $id;   //ID为5691
            $where['admin_id'] = $this->accountId;  //账号1241
            //dump($id);die;


            $res = db('goods')->where($where)->update($data);
        //echo $res;die;

        //var_dump(db('goods')->getlastsql());die;
         //echo DB::name('goods')->getlastsql();
        //dump($data);exit;

            if ($res) { 
                return 1;
            }else{
                return 2;
            }
            
         
        }
        $find = "a.*";
        $res = db('goods')->alias('a')
             ->field($find)
             ->join('goods_category b','a.category_id = b.id','LEFT') //获取商品信息
             ->where("a.id",input('id'))
             ->find();
            //dump($res);exit;
             $arr = DB::name("goods_category")->where("id",$res['category_id'])->field("id,title")->find();
             //dump($arr);exit;
             if($arr){
                $res['fy'] = $arr['title'];  //显示商品类别和ID
                $res['fy_id'] = $arr['id'];
             }else{
                $res['fy'] = '';
                $res['fy_id'] = '';
             }
        // //规格二维数组
        // //转换json为数组格式
        // $where=array();
        // $where['goods_id']=$res['id'];
        // $res['user_id']==0||$res['user_id']==null?"":$where['user_id']=$res['user_id'];
        // $where['admin_id']=$res['admin_id'];
        // $field=['id','key','val','price'];
        // $res['param']=db('param')->field($field)->where($where)->select();

        //dump($res['param']);die;
        //拿到数据库图片地址所以URL
        $imges = $res['imgs'];
        $imges1 = '';
        $imges2 = '';
        $imges3 = ''; 
        if (!empty($imges)) {
            //转换格式
            $imges = json_decode($imges, true);
            foreach ($imges as $k => $v) {
                if (isset($imges[0])) {
                    $imges1 = $imges[0];
                }else{
                    $imges1 = '';
                }
                if (isset($imges[1])) {
                    $imges2 = $imges[1];
                }else{
                    $imges2 = '';
                }
                if (isset($imges[2])) {
                    $imges3 = $imges[2];
                }else{
                    $imges3 = '';
                }

            }
        }


        //获取商品分类
        $where =[];
        $kv = $this->accountId;
        $where['admin_id'] = $this->accountId;
        $cate = db('goods_category')->where($where)->limit(100)->select();
         //echo DB::name('goods_category')->getlastsql();
        //dump($cate);exit;

        $Singer = db('singer')->where("admin_id='{$this->accountId}'")->select();
        $this->assign('Singer', $Singer);

        $cate = getCategory($cate, 0);
        $this->assign('cate', $cate);
        $this->assign('res', $res);
        $this->assign('kv',$kv);


        $this->assign('imges1', $imges1);
        $this->assign('imges2', $imges2);
        $this->assign('imges3', $imges3);
        return $this->fetch();
    }

    /**
     * 商品规格列表展示
     */
    
    public function goodsattrlist($id)
    {
       
        $where['admin_id'] = $this->accountId;
        $where['goods_id'] = input('id');
        $where['parent_id'] = 0;
        $res = db('goods_attr')->where($where)->select();
        foreach ($res as $key => $value) {
            $res[$key]['children'] = db('goods_attr')->where("admin_id='{$where['admin_id']}' and parent_id='{$value['id']}' and goods_id='{$where['goods_id']}'")->select();
            foreach ($res[$key]['children'] as $k => $v) {
                 $res[$key]['children'][$k]['attr'] = db('goods_attr')->where("admin_id='{$where['admin_id']}' and parent_id='{$v['id']}' and goods_id='{$where['goods_id']}'")->select();
                 $res[$key]['children'][$k]['count'] = db('goods_attr')->where("admin_id='{$where['admin_id']}' and parent_id='{$v['id']}' and goods_id='{$where['goods_id']}'")->count();
            }
        }
        //$res = getCategory($res, 0);
 
  
        $this->assign('goods_id', input('id'));
        $this->assign('res', $res);
        return $this->fetch();
    }

    /***
      *商品规格添加
      * 
      */
    public function goodsattradd(Request $request,$goods_id)
    {
        
       if (request()->isPost()) {
            $post = request()->only(['parent_id,name,price,their_id'], 'post');

            $data['admin_id'] = $this->accountId;
            $data['goods_id'] = $goods_id;
            $data['parent_id'] = $_POST['parent_id'];
            
            // if ($this->accountId == 1301) {
            //     $data['their_id'] = $_POST['their_id'];
            // }
            
            $data['name'] = $_POST['name'];
            $data['price'] = $_POST['price'];
            $res = db('goods_attr')->insert($data);
        
            if ($res) {
                return 1;
            }else{
                return 2;
            }
        }

        $where =[];
        $where['goods_id'] = $goods_id; 
        $where['admin_id'] = $this->accountId;
        $cate = db('goods_attr')->where($where)->limit(100)->select();
        $cate = getCategory($cate, 0);
        $this->assign('cate', $cate);
        $this->assign('goods_id', $goods_id);
        $this->assign('admin_id', $this->accountId);
        return $this->fetch();
    }
    
    // 增加商品属性分类
    public function goodsAddCategory()
    {
        $post = request()->only(['name', 'goods_id'], 'post');

        $post['parent_id'] = 0;
        $post['admin_id'] = $this->accountId;
        $post['create_time'] = time();
        $res = db('goods_attr')->insert($post);
    
        if ($res) {
            return 1;
        }else{
            return 2;
        } 
    }

    /***
      *商品规格编辑
      */
    public function goodsattredit($id)
    {

        $sk = $this->accountId; 
        if (request()->isPost()) {
            $post=input('post.');

            if(empty($post['name'])){
                err('','名称不能为空');
            }
            $where=[];
            $where['id'] = $id;
            $result = db('goods_attr')->where($where)->update($post);

            //返回更新结果
            if($result){
                return 1;
            }
            else{
                return 2;
            }
        } 
    
        $where = [];
        $where['id'] = $id;
        $where['admin_id'] = $this->accountId;
        $res = db('goods_attr')->where($where)->find();
        $ress = db('goods_attr')->field('parent_id')->where($where)->find();

        $this->assign('ress', $ress);
        $this->assign('res', $res);
        return $this->fetch();
    }

    //商品规格删除
    public function goodsattrdel($id)
    {        
            $arr = db('goods_attr')->where(['id'=>$id])->field('parent_id')->find();
            if ($arr['parent_id'] == 0) {
                $where = [];
                $where['parent_id'] = $id;
                $where['admin_id'] = $this->accountId;
                db('goods_attr')->where($where)->delete();
            }
            $where = [];
            $where['id'] = $id;
            $where['admin_id'] = $this->accountId;
            $res = db('goods_attr')->where($where)->delete();
            suc();
    }
    /***
     *
     *生成二维码入库
     *
     */
    public function OrCode($id)
    {
        $post = request()->only(['rqcode'], 'post');
        $post['admin_id']=$this->accountId;
        $post['name']="aaww";
        $post['scene']='scene';
        $post['user_id']='1333';
        $where = [];
        $where['admin_id']  = $this->accountId;
        $data = array();
        $where['id']  = $id;
        //dump($where['id']);die;
        $res  = db('goods')->where($where)->find();
        //dump($res);exit;
         //如果已经生成过二维码，直接返回二维码数据
        if (!empty($res['rqcode'])) {
            $this->assign('imges', $res['rqcode']);
            //return $this->fetch();

        }
        // 根目录
        $root = ROOT_PATH . 'public' . DS;  //"D:\xiangm\applet\public\"

        //dump($root);exit;

        // 主背景图片
        $path = 'uploads' . DS . 'mobile.jpg';  // "uploads\mobile.jpg"


        if (!file_exists($root . $path)) {
            err('', '背景图片不存在');
        }
        // 读取背景图片
        $image = \think\Image::open($root . $path);
        //dump($image);exit;
        // 二维码缩略图参数
        $post['width'] = 250;
        $post['height'] = 250;

         // 获取小程序二维码 - 缩略图
        $weixin = new Weixin();
        $post['sign_id'] = 'goods_id='.$id;  //接收ID
        $imgRqcode = $weixin->getRqcodeB($post);

        // 字体文件
        $font = $root . 'uploads' . DS . 'msyh.ttf';
        $imgShare = 'uploads' . DS . $post['admin_id'] . DS . 'user' . DS . 'long-press-' . time() . '.jpg';
        //dump($imgShare);exit;
        $title = '# ' . mb_substr($res['title'], 0, 10, 'utf-8') . ' #';

    
        // 拼接图片
        $image->text($title, $font, 18, '#FF8C69', 2, [0, 30])// 标题
        ->water($imgRqcode, [85, 70], 100)// 二维码
        // ->text($footText, $font, 12, '#B9B9B9', 8, [0, -18])// 说明
        ->save($root . $imgShare);
        $imgUrl = 'http://api.wei-yong.com/' . $imgShare . '?v=' . $this->timeStamp;  //打印出来的地址可以放在线上查看有没有图片
        //dump($imgUrl);exit;
        //将圈子信息存入
        $data['rqcode'] = $imgUrl;
        //dump($data['rqcode']);exit;
        $res = db('goods')->where($where)->update($data);

        $this->assign('imges', $imgUrl);
        return $this->fetch();
        
    }


   
  

    /**
     *参数配置列表
     */
    public function param()
    {
        $where = [];
        $where['admin_id'] = $this->accountId;
        $field = [];
        $res = db('param')->where($where)->field($field)->order('id asc')->paginate($this->page,false);  
        $res1 = array();
        foreach ($res as $k=>$v){
            $res1[$k] = $v;
            $res1[$k]['val'] = is_array(json_decode($v['val'])) ? implode(',',json_decode($v['val'])):json_decode($v['val']);
        }
        $page = $res->render();
        $this->assign('res', $res1);
        $this->assign('page', $page);
        return $this->fetch();

    }

    /**
     *参数配置添加
     */
    public function paramadd()
    {

         if (request()->isPost()) {    
          $post = request()->only(['key', 'val']);
          $post['val'] = json_encode($post['val']);
          //dump($post['val']);exit;
          $post['admin_id'] = $this->accountId;  //只允许后台登录用户查看
          $post['create_time'] = time();
          $res = db('param')->insert($post);
            suc();
        }
       return  $this->fetch();
    }


    //商品搜索
    public function searchlist()
    {
        if (request()->isPost()) {
            $post = request()->only(['search'], 'post');
            $title = $post['search'];

            $where = [];
            $where['admin_id'] = $this->accountId;
            $res = db('goods')->where("title like '{$title}%'")->where($where)->paginate($this->page,false);
        }
        $page = $res->render();
        $this->assign('res', $res);
        $this->assign('page', $page);
        return $this->fetch();
    }



    //商品评论标签管理
    public function comment_category()
    {
        $res = db('goods_comment_category')->where("admin_id='$this->accountId'")->order('id desc')->paginate($this->page, false);
        $page = $res->render();
        $this->assign('res', $res);
        $this->assign('page', $page);
        return $this->fetch();
    }


    //添加商品评论标签
    public function comment_category_add()
    {
        if (request()->isPost()) {
            $post = input('post.');

             #判断区
            if (empty($post['goods_id'])) {
                err('','商品ID不能为空');
            }   
            if (empty($post['title'])) {
                err('','分类标题不能为空');
            }

            #组合数据区
            $data['admin_id'] = $this->accountId;
            $data['create_time'] = time();
            $data['title'] = $post['title'];
            $data['numbs'] = $post['numbs'];
            $data['goods_id'] = $post['goods_id'];
            
            #执行区
            $res = db('goods_comment_category')->insert($data);
            if ($res) {
                suc('','添加成功');
            }else{
                err('','添加失败');
            }

        }else{
           return $this->fetch();  
        }
    }


    //编辑商品评论标签
    public function comment_category_edit($id)
    {
        if (request()->isPost()) {
            $post = input('post.');

            #判断区
            if (empty($post['goods_id'])) {
                err('','商品ID不能为空');
            }
            if (empty($post['title'])) {
                err('','分类标题不能为空');
            }

            #组合数据区
            $data['create_time'] = time();
            $data['title'] = $post['title'];
            $data['numbs'] = $post['numbs'];
            $data['goods_id'] = $post['goods_id'];
            
            #执行区
            $res = db('goods_comment_category')->where(['id'=>$id,'admin_id'=>$this->accountId])->update($data);
            if ($res) {
                suc('','编辑成功');
            }else{
                err('','编辑失败');
            }

        }else{
            $res = db('goods_comment_category')->where(['id'=>$id,'admin_id'=>$this->accountId])->find();
            $this->assign('res', $res);
            return $this->fetch();  
        }
    }


    //删除商品评论标签
    public function comment_category_del($id)
    {
        $res = db('goods_comment_category')->where(['id'=>$id,'admin_id'=>$this->accountId])->delete();
        suc();
    }


}
